<script setup lang="ts">
import { reactive, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { useDebounceFn } from '@vueuse/core';
import {
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Row,
  Select,
  Switch,
  Table,
} from 'ant-design-vue';

import { getWarehouseList } from '#/api/common';
import { CreateSendOrder, getProductSnApi } from '#/api/spuBom';

import product from '../../../../modules/product.vue';
import sendPurchaseConfig from './sendPurchaseConfig.vue';
import dayjs from "dayjs";

const emit = defineEmits(['refresh']);

const selectRows: any = ref([]);

const columns1: any = [
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
  },
  {
    title: '实际面料',
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
      },
      {
        title: '本次供应商',
        dataIndex: 'SupplyNa',
        key: 'SupplyNa',
        align: 'center',
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
      },
    ],
  },
  {
    title: '需求量(系统)',
    dataIndex: 'need_num',
    key: 'need_num',
    align: 'center',
  },
  {
    title: '已收数量',
    dataIndex: 'reviced_num',
    key: 'reviced_num',
    align: 'center',
  },
  {
    title: '已发数量',
    dataIndex: 'send_num',
    key: 'send_num',
    align: 'center',
  },
  { title: '未发数量', dataIndex: 'num', key: 'num', align: 'center' },
  {
    title: '采购明细配置/本次发料数量',
    dataIndex: 'purchase',
    key: 'purchase',
    align: 'center',
  },
];

const Options = ref([]);
const loading = ref(false);
const warehouseSearch = useDebounceFn(async (keyword) => {
  loading.value = true;
  try {
    const res = await getWarehouseList({
      quick_search: keyword || '',
      page: 1,
      limit: 20,
      params: { type: '物料', is_stop: '0' },
      order: 'weight,desc',
    });

    Options.value = res.list.map((it: any) => ({
      label: `${it.warehouse_code}/${it.warehouse_name}`,
      value: it.id,
    }));
  } finally {
    loading.value = false;
  }
}, 300);

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const warehouseDropdown = (open) => {
  if (open && Options.value.length === 0) {
    warehouseSearch('');
  }
};

// 生产单
const [Modal, modalApi] = useVbenModal({
  class: 'w-2/3',
  appendToMain: true,
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 验证采购明细配置/本次发料数量
    const emptyRows = [];
    selectRows.value.forEach((row, index) => {
      // 检查num是否为0、空字符串或未定义
      if (row.num === 0 || row.num === '' || row.num === undefined || row.num === null) {
        emptyRows.push(index + 1); // 行号从1开始计数
      }
    });

    if (emptyRows.length > 0) {
      // 有未填写的行，显示错误提示
      const rowsStr = emptyRows.join('、');
      message.error(`第 ${rowsStr} 行的采购明细配置/本次发料数量不能为空或0，请填写后再保存！`);
      return; // 阻止提交
    }

    modalApi.lock(true);
    const params = {
      warehouse_id: formModel.warehouse_id,
      warehouse_name: formModel.warehouse_name,
      is_cf: formModel.is_cf,
      send_date: formModel.send_date,
      goods_no: formModel.goods_no,
      product_sn: formModel.product_sn,
      factory_name: formModel.factory_name,
      list: selectRows.value,
    };

    CreateSendOrder(params).then((res) => {
      modalApi.unlock();
      if (res.data.code === 1) {
        modalApi.close();
        emit('refresh');
        message.success(res.data.msg);
      } else {
        message.error(res.data.msg);
      }
    });
  },
  onOpenChange: async (isOpen: boolean) => {
    warehouseSearch('');
    if (!isOpen) return;
    const { data, id, purchase_id } = modalApi.getData<Record<string, any>>();

    getProductSnApi({ id }).then((res) => {
      if (res.data.code === 0) {
        modalApi.close();
      } else {
        if (res.data.data.product_sn === undefined) {
          message.error(
            '未获取到制单号，请检查大货采购单是否审核，如已审核还提示此错误可联系IT',
          );
        } else {
          message.success('系统获取到应发料制单号,已自动填充');
          formModel.goods_no = res.data.data.goods_no || '';
          formModel.product_sn = res.data.data.product_sn || '';
          formModel.factory_name =
            `${res.data.data.SupplyCode}${res.data.data.SupplyNa}` || '';
        }
      }
    });
    formModel.id = id;
    selectRows.value = data;
    formModel.purchase_id = purchase_id;
  },
});
const formModel = reactive({
  id: '',
  purchase_id: '',
  warehouse_id: '',
  warehouse_name: '',
  product_sn: '',
  factory_name: '',
  goods_no: '',
  remark: '',
  is_cf: false,
  send_date: dayjs(new Date()).format('YYYY-MM-DD'),
});

function changeWarehouse_id(value, options) {
  formModel.warehouse_name = options.label;
}

const [productModal, productModalApi] = useVbenModal({
  connectedComponent: product,
});

// 打开生产单
function openModel() {
  productModalApi.setData({}).open();
}
function changeData(data: any) {
  formModel.product_sn = data.production_sn;
  formModel.factory_name = `${data.follow_order.SupplyCode}/${data.follow_order.SupplyNa}`;
  formModel.goods_no = data.goods_no;
}

// 打开采购明细
const dataIndex: any = ref();
function openPurchaseDetails(open: any, index: any) {
  dataIndex.value = index;
  const data = JSON.parse(JSON.stringify(open));
  sendPurchaseConfigModalApi.setData({ data: data.sku_list }).open();
}

const [sendPurchaseConfigModal, sendPurchaseConfigModalApi] = useVbenModal({
  connectedComponent: sendPurchaseConfig,
});

function changesendPurchaseConfig(data: any) {
  let totalNum = 0;
  for (const item of data) {
    totalNum += item.num;
  }
  selectRows.value[dataIndex.value].sku_list = data;
  selectRows.value[dataIndex.value].num = totalNum;
}
</script>

<template>
  <Modal title="确认发料？">
    <Page>
      <Form :label-col="{ span: 7.5 }" :model="formModel">
        <Row :gutter="[15, 0]">
          <Col :span="4">
            <FormItem name="reqCode" label="日期">
              <DatePicker
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                v-model:value="formModel.send_date"
              />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="发出仓库">
              <Select
                v-model:value="formModel.warehouse_id"
                show-search
                allow-clear
                style="width: 100%; height: 100%"
                placeholder="请输入"
                :filter-option="false"
                :options="Options"
                :loading="loading"
                @search="warehouseSearch"
                @change="changeWarehouse_id"
                @dropdown-visible-change="warehouseDropdown"
              />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="生产单">
              <Input v-model:value="formModel.product_sn" @click="openModel()" disabled/>
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="货号">
              <Input v-model:value="formModel.goods_no" disabled />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="加工厂">
              <Input v-model:value="formModel.factory_name" disabled />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="备注">
              <Input v-model:value="formModel.remark" />
            </FormItem>
          </Col>
          <Col :span="4">
            <FormItem name="reqCode" label="支持超发">
              <Switch v-model:checked="formModel.is_cf" />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Table
        class="w-fill"
        bordered
        :data-source="selectRows"
        :columns="columns1"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'purchase'">
            <div
              style="color: #409eff"
              @click="openPurchaseDetails(record, index)"
            >
              <u>{{ record.num }}</u>
            </div>
          </template>
        </template>
      </Table>
    </Page>
  </Modal>
  <productModal @push-data="changeData" />
  <sendPurchaseConfigModal @push-data="changesendPurchaseConfig" />
</template>

<style scoped></style>
